package com.spring.pick2pick.common;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;

public class ApiHandler extends WebHandler {

	public static class XmlData {
		private String key;
		private Object value;

		public XmlData(String key, int value) {
			super();
			this.key = key;
			this.value = new Integer(value);
		}

		public XmlData(String key, double value) {
			super();
			this.key = key;
			this.value = new Double(value);
		}

		public XmlData(String key, String value) {
			super();
			this.key = key;
			this.value = value;
		}

		public String getKey() {
			return key;
		}

		public Object getValue() {
			return value;
		}

	}

	private String apiName = null;

	public ApiHandler(HttpServletRequest request, JspWriter out, String apiName) {
		super(request, out);
		this.apiName = apiName;
	}
	
	public void result(String rt, String msg) {
		this.result(rt, msg, null);
	}

	public void result(String rt, String msg, ArrayList<XmlData> data) {
		if (rt == null) {
			rt = "ERROR";
		}
		
		String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
		xml += "<%s>\n";
		xml += "\t<rt>%s</rt>\n";
		xml += "\t<rtmsg><![CDATA[ %s ]]></rtmsg>\n";
		
		if (data != null) {
			for (int i=0; i<data.size(); i++) {
				XmlData item = data.get(i);
				
				if (item != null) {
					xml += "\t<" + item.getKey() + "><![CDATA[ " + item.getValue() + " ]]></" + item.getKey() + ">\n";
				}
			}
		}
		
		xml += "</%s>";
		try {
			out.print(String.format(xml, this.apiName, rt, msg, this.apiName));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
